<?php
/**
 * @version $Id: admin.unocloud.php 3 2010-05-25 14:59:16Z vladzimirs $
 * @package UnoCloud
 * @copyright Авторские права (C) 2009-2010 UnoCloud team & (C) 2007-2010 Joostina team &. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * UnoCart! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл help/copyright.php.
 */
defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');

if (!($acl->acl_check('administration', 'edit', 'users', $my->usertype,
    'components', 'all') | $acl->acl_check('administration', 'edit', 'users', $my->
    usertype, 'components', 'com_unocloud'))) {
    mosRedirect('index2.php', _NOT_AUTH);
}

require_once ($mainframe->getPath('admin_html'));

global $mosConfig_absolute_path, $UNOCLOUD_version;

$UNOCLOUD_version = "1.0 alfa";

if (!@include_once ($mosConfig_absolute_path .
    "/administrator/components/com_unocloud/language/" . $mosConfig_lang . ".php")) {
    include_once ($mosConfig_absolute_path .
        "/administrator/components/com_unocloud/language/russian.php");
}
//require($mosConfig_absolute_path."/administrator/components/com_unocloud/settings.php");


$task = mosGetParam($_REQUEST, 'task');
$no_html = mosGetParam($_REQUEST, 'no_html');
$plid = mosGetParam($_REQUEST, 'plid');
$cid = josGetArrayInts('cid');
$option = "com_unocloud";

require ($mosConfig_absolute_path .
    "/administrator/components/com_unocloud/includes/config.class.php");
require ($mosConfig_absolute_path .
    "/administrator/components/com_unocloud/includes/tag.creator.class.php");

$UNOCLOUD_config = new UnoCloud_config();
$tagCreator = new UnoCloud_TagCreator($UNOCLOUD_config);

switch ($task) {
    case 'upload':
        upload($option);
        break;
    case 'publish':
        publishWord($cid, 1, $option);
        $tagCreator->setFontSize();
        viewWords($option);
        break;
    case 'unpublish':
        publishWord($cid, 0, $option);
        $tagCreator->setFontSize();
        viewWords($option);
        break;
    case 'publishPlugin':
        publishPlugin($plid, 1, $option);
        break;
    case 'unpublishPlugin':
        publishPlugin($plid, 0, $option);
        break;
    case 'config':
        showConfig($option, $UNOCLOUD_config);
        break;
    case 'saveconfig':
        saveConfig($option);
        //viewWords( $option );
        mosRedirect("index2.php?option=$option&task=refresh", UNOCLOUD_SAVED);
        break;
    case 'create':
        $tagCreator->createCloudArray();
        viewWords($option);
        //mosRedirect( "index2.php?option=$option&task=view" );
        break;
    case 'eraseAll': //disabled
        emptyDatabase($option);
        mosRedirect("index2.php?option=$option");
        break;
    case 'eraseUnpubl':
        eraseUnpublished($option);
        mosRedirect("index2.php?option=$option");
        break;
    case 'removeWords':
        $eraseDes = true;
        viewWords($option);
        break;
    case 'plugins':
        plugins($option);
        break;
    case 'removePlugin':
        removePlugin($plid, $option);
        break;
    case 'refresh':
        //eraseUnpublished($option);
        //$tagCreator->createCloudArray ();
        viewWords($option);
        break;
    case 'view':
        viewWords($option);
        break;
    case 'addBlacklist':
        addBlacklist($cid, $option);
        viewWords($option);
        break;
    case 'sortBlacklist':
        echo (sortBlacklist());
        break;
    default:
        viewWords($option);
        break;
}

function viewWords($option)
{
    global $database, $mainframe, $mosConfig_list_limit;

    $search = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
    $search = $database->getEscaped(trim($search));

    $showPublished = $mainframe->getUserStateFromRequest("showPublished{$option}",
        'showPublished', '');
    $showPublished = $database->getEscaped(trim($showPublished));

    $orderby = mosGetParam($_REQUEST, 'orderby', 'counter');
    $sort = mosGetParam($_REQUEST, 'ordering', 'DESC');
    $limit = intval($mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit));
    $limitstart = intval($mainframe->getUserStateFromRequest("viewban{$option}limitstart",
        'limitstart', 0));
    if (!empty($search))
        $r_search = " WHERE word LIKE '%$search%' ";
    else
        $r_search = null;

    $query = "SELECT COUNT(*)" . "\n FROM #__unocloud_stat " . $r_search .
        " ORDER BY " . $orderby . " " . $sort . " , word ASC";
    $database->setQuery($query);
    $total = $database->loadResult();

    require_once ($GLOBALS['mosConfig_absolute_path'] .
        '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav($total, $limitstart, $limit);


    $query = "SELECT * FROM #__unocloud_stat " . $r_search . " ORDER BY " . $orderby .
        " " . $sort . " , word ASC LIMIT $pageNav->limitstart,$pageNav->limit";
    $database->setQuery($query);
    $rows = $database->loadObjectList();

    HTML_unocloud::showWords($rows, $pageNav, $option, $search, $sort, $orderby, $showPublished);
}

function sortBlacklist()
{
    global $UNOCLOUD_config;
    $UNOCLOUD_blacklist = $UNOCLOUD_config->getValue("UNOCLOUD_blacklist");
    $blist = explode(",", Jstring::str_ireplace(" ", "", $UNOCLOUD_blacklist));
    $blist = array_unique($blist);
    sort($blist);
    $blist = implode(",<br>", $blist);
    return $blist;
}

function publishWord($cid = null, $publish = 1, $option)
{
    global $database, $my;

    if (!is_array($cid) || count($cid) < 1) {
        $action = $publish ? 'publish' : 'unpublish';
        echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
        exit;
    }

    $cids = implode(',', $cid);

    $database->setQuery("UPDATE #__unocloud_stat SET dateAdd=now(), published='$publish'" .
        "\nWHERE id IN (" . $cids . ")");
    if (!$database->query()) {
        echo "<script> alert('" . $database->getErrorMsg() .
            "'); window.history.go(-1); </script>\n";
        exit();
    }
}

function addBlacklist($cid = null, $option)
{
    global $database, $my;

    $UNOCLOUD_config = new UnoCloud_config();
    if (!is_array($cid) || count($cid) < 1) {
        echo "<script> alert('Select an item to blacklist'); window.history.go(-1);</script>\n";
        exit;
    }

    $cid = $cid[0];
    $database->setQuery("SELECT * FROM #__unocloud_stat WHERE id=" . $cid);
    if ($database->loadObject($row)) {
        $word = $row->word;
        $database->setQuery("DELETE FROM #__unocloud_stat WHERE id =" . $cid);
        if (!$database->query()) {
            echo "<script> alert('" . $database->getErrorMsg() .
                "'); window.history.go(-1); </script>\n";
            exit();
        } else {
            $UNOCLOUD_blacklist = $UNOCLOUD_config->getValue("UNOCLOUD_blacklist");
            if (empty($UNOCLOUD_blacklist))
                $UNOCLOUD_blacklist = $word;
            else
                $UNOCLOUD_blacklist .= ", " . $word;

            $UNOCLOUD_config->setValue("UNOCLOUD_blacklist", $UNOCLOUD_blacklist, 'config');
        }
    } else {
        echo "<script> alert('" . $database->getErrorMsg() .
            "'); window.history.go(-1); </script>\n";
        exit();
    }
}

function removeBlacklisted()
{

}

function emptyDatabase($option)
{
    global $database;
    $database->setQuery("DELETE FROM #__unocloud_stat");
    $database->query();
}

function eraseUnpublished($option)
{
    global $database;
    $database->setQuery("DELETE FROM #__unocloud_stat WHERE published=0");
    $database->query();
}


function publishPlugin($plid = null, $publish = 1, $option)
{
    global $database, $my;

    if (!is_array($plid) || count($plid) < 1) {
        $action = $publish ? 'publish' : 'unpublish';
        echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
        exit;
    }

    $plids = implode(',', $plid);
    $plids = str_replace(",", "','", $plids);

    $database->setQuery("UPDATE #__unocloud_plugins SET published='$publish' " . "\nWHERE plugin IN ('" .
        $plids . "')");
    if (!$database->query()) {
        echo "<script> alert('" . $database->getErrorMsg() .
            "'); window.history.go(-1); </script>\n";
        exit();
    }
    mosRedirect("index2.php?option=$option&task=plugins");
}

function removePlugin($plid = null, $option)
{
    global $database, $mosConfig_dbprefix, $mosConfig_absolute_path;
    $dir = $mosConfig_absolute_path .
        "/administrator/components/com_unocloud/plugins/";
    if (!is_array($plid) || count($plid) < 1) {
        echo "<script> alert('Select an item to remove'); window.history.go(-1);</script>\n";
        exit;
    }

    foreach ($plid as $plugin) {
        $database->setQuery("SELECT * FROM #__unocloud_plugins WHERE plugin='" . $plugin .
            "'");
        if ($database->loadObject($row)) {
            //$plugin=$row->plugin;
            $database->setQuery("DELETE FROM #__unocloud_plugins WHERE plugin ='" . $plugin .
                "'");
            if ($database->query()) {
                if (!unlink($dir . $plugin)) {
                    echo "<script> alert('Error unlink file!'); window.history.go(-1); </script>\n";
                    exit();
                }
            } else {
                echo "<script> alert('" . $database->getErrorMsg() .
                    "'); window.history.go(-1); </script>\n";
                exit();
            }
        }
    }
    mosRedirect("index2.php?option=$option&task=plugins");
}


/*Configuratior*/
function showConfig($option = 'com_unocloud', &$UNOCLOUD_config)
{
    HTML_unocloud::settings($option, $UNOCLOUD_config);
}

function saveConfig($option)
{

    global $mosConfig_absolute_path, $database;

    if (($_POST['remove_database'] == 1) && ($_POST['remove_database_1'])) {
        $database->setQuery("DROP TABLE `#__unocloud_config`;");
        if (!$database->query())
            mosRedirect("index2.php?option=$option", "unocloud_config - " . UNOCLOUD_ERROR);
        $database->setQuery("DROP TABLE `#__unocloud_plugins`;");
        if (!$database->query())
            mosRedirect("index2.php?option=$option", "unocloud_plugins - " . UNOCLOUD_ERROR);
        $database->setQuery("DROP TABLE `#__unocloud_stat`;");
        if (!$database->query())
            mosRedirect("index2.php?option=$option", "unocloud_stat - " . UNOCLOUD_ERROR);

        mosRedirect("index2.php?option=com_installer&element=component",
            UNOCLOUD_REMOVED);
        //mosRedirect("index2.php?option=$option", UNOCLOUD_REMOVED);
        return;
    }

    $UNOCLOUD_config = new UnoCloud_config();
    $UNOCLOUD_config->setValue("UNOCLOUD_enabled", $_POST['words_enabled'], 'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_published", $_POST['published'], 'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_min_counter", $_POST['mincounter'],
        'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_min_len", $_POST['minlen'], 'config');
    if ($_POST['maxlen'] > 200)
        $ml = 200;
    else
        $ml = $_POST['maxlen'];
    $UNOCLOUD_config->setValue("UNOCLOUD_max_len", $ml, 'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_blacklist", $_POST['blacklist'], 'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_whitelist", $_POST['whitelist'], 'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_min_font", $_POST['minfont'], 'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_max_font", $_POST['maxfont'], 'config');

    $UNOCLOUD_config->setValue("UNOCLOUD_run_period", $_POST['run_period'],
        'scheduler');
    $UNOCLOUD_config->setValue("UNOCLOUD_run_period_unit", $_POST['period_unit'],
        'scheduler');
    $UNOCLOUD_config->setValue("UNOCLOUD_run_limit", $_POST['run_limit'],
        'scheduler');
    $UNOCLOUD_config->setValue("UNOCLOUD_admin_email", $_POST['admin_email'],
        'scheduler');
    $UNOCLOUD_config->setValue("UNOCLOUD_run_hour", $_POST['run_hour'], 'scheduler');
    $UNOCLOUD_config->setValue("UNOCLOUD_run_minute", $_POST['run_minute'],
        'scheduler');
    $UNOCLOUD_config->setValue("UNOCLOUD_run_day", $_POST['run_day'], 'scheduler');
    $UNOCLOUD_config->setValue("UNOCLOUD_run_month", $_POST['run_month'],
        'scheduler');
    $UNOCLOUD_config->setValue("UNOCLOUD_run_year", $_POST['run_year'], 'scheduler');

    $UNOCLOUD_config->setValue("UNOCLOUD_preg_replace", $_POST['replace_pattern'],
        'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_str_lower", $_POST['str_lower'], 'config');


    $UNOCLOUD_config->setValue("UNOCLOUD_key_enabled", $_POST['key_enabled'],
        'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_key_published", $_POST['key_published'],
        'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_key_min_counter", $_POST['key_mincounter'],
        'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_key_min_len", $_POST['key_minlen'],
        'config');
    if ($_POST['key_maxlen'] > 200)
        $ml = 200;
    else
        $ml = $_POST['key_maxlen'];
    $UNOCLOUD_config->setValue("UNOCLOUD_key_max_len", $ml, 'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_key_whitelist", $_POST['key_whitelist'],
        'config');

    $UNOCLOUD_config->setValue("UNOCLOUD_key_preg_replace", $_POST['key_replace_pattern'],
        'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_key_str_lower", $_POST['key_str_lower'],
        'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_key_asword", $_POST['key_asword'], 'config');

    $UNOCLOUD_config->setValue("UNOCLOUD_on_cache", $_POST['cache'], 'config');
    $UNOCLOUD_config->setValue("UNOCLOUD_sh404sef_prefix", $_POST['sh404p'],
        'config');

    //$UNOCLOUD_config->setValue("", $_POST[''],'config');

    if (is_file($mosConfig_absolute_path .
        "/administrator/components/com_unocloud/settings.php")) {
        if (!unlink($mosConfig_absolute_path .
            "/administrator/components/com_unocloud/settings.php"))
            mosRedirect("index2.php?option=$option", UNOCLOUD_ERROR_REMCONF);
    }
    if ($_POST['resetrun'])
        unlink($mosConfig_absolute_path .
            "/administrator/components/com_unocloud/runlog.php");

}


function loadPluginDescr($plugin)
{
    global $mosConfig_absolute_path;
    $fname = $mosConfig_absolute_path .
        "/administrator/components/com_unocloud/plugins/" . $plugin;

    $file = @fopen($fname, "r");
    if ($file) {
        $isDes = false;
        $isPackage = false;
        $isVersion = false;
        while (!feof($file)) {
            $buffer = fgets($file, 4096);
            echo ($buffer);
            if (strpos($buffer, "descr") !== false)
                $isDes = true;
            if (strpos($buffer, "@package UnoCloud") !== false)
                $isPackage = true;
            if (strpos($buffer, "@version 1.") !== false)
                $isVersion = true;
        }
        fclose($file);
        if ($isDes && $isPackage && $isVersion) {
            $runMe = false;
            include ($mosConfig_absolute_path .
                "/administrator/components/com_unocloud/plugins/" . $plugin);
            if (empty($descr))
                return null;
            return $descr;
        }
    }
    return null;
}

function savePluginInfo($plugin)
{
    global $database, $mosConfig_dbprefix, $mosConfig_absolute_path;
    $dir = $mosConfig_absolute_path .
        "/administrator/components/com_unocloud/plugins/";
    $plugin = strtolower($plugin);
    if ($descr = loadPluginDescr($plugin)) {
        $database->setQuery("SELECT * FROM " . $mosConfig_dbprefix .
            "unocloud_plugins WHERE plugin='" . $plugin . "'");
        if ($database->loadObject($row)) {
            $database->setQuery("UPDATE " . $mosConfig_dbprefix .
                "unocloud_plugins SET descr='" . $descr . "' WHERE plugin='" . $plugin . "'");
        } else {
            $database->setQuery("INSERT INTO " . $mosConfig_dbprefix .
                "unocloud_plugins (plugin,descr) VALUES ('" . $plugin . "','" . $descr . "')");
        }
        $database->query();
    } else {
        if (!unlink($dir . $plugin)) {
            echo "<script> alert('Error unlink file!'); window.history.go(-1); </script>\n";
            exit();
        }
        mosRedirect("index2.php?option=com_unocloud&task=plugins", UNOCLOUD_ERROR_PLUGIN);
    }

}


function upload($option)
{
    global $mosConfig_absolute_path;
    $dir = $mosConfig_absolute_path .
        "/administrator/components/com_unocloud/plugins/";

    $file = mosGetParam($_FILES, 'rcfile', null);

    if (isset($file) && is_array($file)) {
        if (strtolower(substr($file['name'], -4)) != ".php")
            mosRedirect("index2.php?option=com_unocloud&task=plugins",
                UNOCLOUD_ERROR_UPLOAD_1 . ".php");

        if (!move_uploaded_file($file['tmp_name'], $dir . strtolower($file['name'])))
            mosRedirect("index2.php?option=com_unocloud&task=plugins",
                UNOCLOUD_ERROR_UPLOAD_2);

    } else
        mosRedirect("index2.php?option=com_unocloud&task=plugins", UNOCLOUD_ERROR_UPLOAD);

    savePluginInfo($file['name']);

    mosRedirect("index2.php?option=com_unocloud&task=plugins", UNOCLOUD_OK_UPLOAD);
}


function plugins($option)
{
    global $mosConfig_absolute_path, $database, $mainframe, $mosConfig_list_limit;
    $limit = intval($mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit));
    $limitstart = intval($mainframe->getUserStateFromRequest("viewban{$option}limitstart",
        'limitstart', 0));
    $query = "SELECT COUNT(*)" . "\n FROM #__unocloud_plugins ";
    $database->setQuery($query);
    $total = $database->loadResult();

    require_once ($GLOBALS['mosConfig_absolute_path'] .
        '/administrator/includes/pageNavigation.php');
    $pageNav = new mosPageNav($total, $limitstart, $limit);


    $query = "SELECT * FROM #__unocloud_plugins ORDER BY plugin";
    $database->setQuery($query);
    $rows = $database->loadObjectList();

    HTML_unocloud::showPlugins($rows, $pageNav, $option);
}


?>